/* eslint-disable jsx-a11y/media-has-caption */
import React from 'react';
import { Icon } from 'antd';
import CurrentTime from './CurrentTime';
import Duration from './Duration';
import ProgressBar from './ProgressBar';
import RateBar from './RateBar';
import VolumeBar from './VolumeBar';
import styles from './index.module.less';

export default function AudioPlayer(props) {
    const {
        onPlayError,
        src,
        showRateBar,
        rates = [0.4, 0.6, 0.8, 1, 1.2, 1.5, 2, 2.5, 3],
        defaultRate = 1,
        showVolumeBar,
        ...rest
    } = props;
    const containerRef = React.useRef();
    const playerRef = React.useRef();
    const [audio, setAudio] = React.useState();
    const [playing, setPlaying] = React.useState(false);

    const playAudioPromise = () => {
        const playPromise = audio.play();
        if (playPromise && onPlayError) {
            playPromise.then(null).catch(err => {
                onPlayError(new Error(err));
            });
        }
    };

    const togglePlay = e => {
        e.stopPropagation();
        if ((audio.paused || audio.ended) && audio.src) {
            playAudioPromise();
        } else if (!audio.paused) {
            audio.pause();
        }
    };

    React.useEffect(() => {
        if (playerRef.current) {
            setAudio(playerRef.current);
        }
    }, []);

    const handleAudioPlay = () => {
        setPlaying(true);
    };

    const handleAudioPause = () => {
        setPlaying(false);
    };

    React.useEffect(() => {
        if (audio) {
            audio.addEventListener('play', handleAudioPlay);
            audio.addEventListener('pause', handleAudioPause);
        }
        return () => {
            if (audio) {
                audio.removeEventListener('play', handleAudioPlay);
                audio.removeEventListener('pause', handleAudioPause);
            }
        };
    }, [audio]);

    return (
        <>
            <audio ref={playerRef} {...rest} src={src} controls style={{ display: 'none' }} />
            {audio && (
                <div className={styles.audioContainer} ref={containerRef}>
                    <Icon
                        type={playing ? 'pause-circle' : 'play-circle'}
                        style={{ fontSize: 20 }}
                        onClick={togglePlay}
                    />
                    <span style={{ marginLeft: 16 }}>
                        <CurrentTime audio={audio} />
                        <span style={{ padding: 4 }}>/</span>
                        <Duration audio={audio} />
                    </span>
                    <ProgressBar audio={audio} />
                    {showRateBar && <RateBar audio={audio} rates={rates} defaultRate={defaultRate} />}
                    {showVolumeBar && <VolumeBar audio={audio} />}
                </div>
            )}
        </>
    );
}
